import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import { StackActions } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useCallback, useState, useRef, useEffect } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  TextInput,
  StatusBar,
  Animated,
  Dimensions,
  Keyboard,
  TouchableWithoutFeedback,
  ScrollView,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Shadow } from 'react-native-shadow-2';

import FastImage from '@d11/react-native-fast-image';
import IconBack from '@svgs/icon_header_back.svg';

import { BusinessAPI } from '@/api/reworkAPI';
import HeaderBar from '@/components/headerBar';
import { RootStackParamList } from '@/types/navigation';
import { pxToVh, pxToVw } from '@/utils/pxToVx';
import { showToast } from '@/utils/showToast';

const { width: SCREEN_WIDTH } = Dimensions.get('window');

// Premium color palette - same as SelectCelebrity
const COLORS = {
  primary: '#2563EB',
  primaryLight: '#3B82F6',
  primaryDark: '#1E40AF',
  secondary: '#6366F1',
  accent: '#8B5CF6',
  background: '#FCFCFF',
  card: '#FFFFFF',
  text: '#1E293B',
  textLight: '#475569',
  textMuted: '#94A3B8',
  border: '#E2E8F0',
  borderLight: '#F1F5F9',
  shadow: 'rgba(0, 0, 20, 0.05)',
  gradient1: '#3B82F6',
  gradient2: '#2563EB',
  gradient3: '#1E40AF',
  gradientLight1: '#EFF6FF',
  gradientLight2: '#DBEAFE',
};

// Mock data for the celebrity list
const mockCelebrityData = [
  {
    id: '1',
    name: 'Elon Musk',
    category: 'Business',
    description: 'Tech Entrepreneur',
    imageUrl: 'https://picsum.photos/id/1/200',
  },
  {
    id: '2',
    name: 'Taylor Swift',
    category: 'Entertainment',
    description: 'Singer & Songwriter',
    imageUrl: 'https://picsum.photos/id/2/200',
  },
  {
    id: '3',
    name: 'Tom Cruise',
    category: 'Entertainment',
    description: 'Actor',
    imageUrl: 'https://picsum.photos/id/3/200',
  },
  {
    id: '4',
    name: 'Emma Watson',
    category: 'Entertainment',
    description: 'Actress & Activist',
    imageUrl: 'https://picsum.photos/id/4/200',
  },
  {
    id: '5',
    name: 'LeBron James',
    category: 'Sports',
    description: 'Basketball Player',
    imageUrl: 'https://picsum.photos/id/5/200',
  },
  {
    id: '6',
    name: 'Serena Williams',
    category: 'Sports',
    description: 'Tennis Player',
    imageUrl: 'https://picsum.photos/id/6/200',
  },
  {
    id: '7',
    name: 'Bill Gates',
    category: 'Business',
    description: 'Entrepreneur & Philanthropist',
    imageUrl: 'https://picsum.photos/id/7/200',
  },
  {
    id: '8',
    name: 'Jeff Bezos',
    category: 'Business',
    description: 'Amazon Founder',
    imageUrl: 'https://picsum.photos/id/8/200',
  },
];

type EnterTextRouteProp = RouteProp<RootStackParamList, 'EnterText'>;

const EnterText = () => {
  const insets = useSafeAreaInsets();
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const route = useRoute<EnterTextRouteProp>();
  const { celebrity } = route.params;

  const [inputText, setInputText] = useState('');

  // Animation values
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const scaleAnim = useRef(new Animated.Value(0.97)).current;

  // Animate component mount
  useEffect(() => {
    // Fade and scale in the main screen
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 400,
        useNativeDriver: true,
      }),
      Animated.timing(scaleAnim, {
        toValue: 1,
        duration: 400,
        useNativeDriver: true,
      }),
    ]).start();
  }, []);

  const handleBack = useCallback(() => {
    // Animate out before navigation
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 200,
        useNativeDriver: true,
      }),
      Animated.timing(scaleAnim, {
        toValue: 0.97,
        duration: 200,
        useNativeDriver: true,
      }),
    ]).start(() => {
      navigation.goBack();
    });
  }, [navigation, fadeAnim, scaleAnim]);

  const navigateToSelectCelebrity = useCallback(() => {
    // Check the navigation state to see if SelectCelebrity screen already exists in the stack
    const state = navigation.getState();
    const selectCelebrityRouteIndex = state.routes.findIndex((route) => route.name === 'SelectCelebrity');

    if (selectCelebrityRouteIndex !== -1) {
      // If SelectCelebrity already exists in the stack, navigate back to it by popping screens
      const popAction = StackActions.pop(state.index - selectCelebrityRouteIndex);
      navigation.dispatch(popAction);
    } else {
      // If not found, navigate to a new SelectCelebrity screen
      navigation.navigate('SelectCelebrity');
    }
  }, [navigation]);

  const handlePreview = useCallback(() => {
    // 调用生成接口
    BusinessAPI.generateVideo({
      characterTemplateId: celebrity.id,
      prompts: [inputText],
    })
      .then((res) => {
        if (res.code == 0) {
          // Navigate to PreviewExport screen with the input text
          navigation.navigate('PreviewExport', {
            videoUrl: 'https://example.com/sample-video.mp4', // This would be the actual generated video URL
            message: inputText,
          });
        } else {
          showToast.toastWarning(res.msg);
        }
      })
      .catch((e) => {
        showToast.toastOperationFailure();
      });
  }, [inputText, navigation, celebrity.id]);

  const handleSuggestionPress = useCallback((suggestion: string) => {
    setInputText(suggestion);
  }, []);

  const handleDismissKeyboard = useCallback(() => {
    Keyboard.dismiss();
  }, []);

  return (
    <Animated.View
      style={[
        styles.container,
        {
          paddingTop: insets.top,
          opacity: fadeAnim,
          transform: [{ scale: scaleAnim }],
        },
      ]}
    >
      <StatusBar backgroundColor={COLORS.background} barStyle="dark-content" />

      {/* Header */}
      <HeaderBar title="Enter Text" leftIcon={<IconBack />} />

      <TouchableWithoutFeedback onPress={handleDismissKeyboard}>
        <ScrollView
          showsVerticalScrollIndicator={false}
          keyboardShouldPersistTaps="handled"
          onScrollBeginDrag={handleDismissKeyboard}
          contentContainerStyle={styles.scrollContent}
        >
          {/* Celebrity Profile Card */}
          {celebrity && (
            <View style={styles.profileCardContainer}>
              <View style={styles.profileCard}>
                <FastImage source={{ uri: celebrity.avtarUrl }} style={styles.profileImage} resizeMode="cover" />
                <View style={styles.profileInfo}>
                  <Text style={styles.profileName}>{celebrity.name}</Text>
                  <Text style={styles.profileDescription}>{celebrity.description}</Text>
                </View>
                <TouchableOpacity style={styles.changeButton} onPress={navigateToSelectCelebrity}>
                  <Text style={styles.changeButtonText}>Change</Text>
                </TouchableOpacity>
              </View>
            </View>
          )}

          {/* Question Text */}
          <View style={styles.questionContainer}>
            <Text style={styles.questionText}>What do you want {celebrity?.name} to say?</Text>
          </View>

          {/* Text Input */}
          <View style={styles.inputContainer}>
            <TextInput
              style={styles.textInput}
              placeholder="Enter your text here..."
              placeholderTextColor={COLORS.textMuted}
              multiline
              value={inputText}
              onChangeText={setInputText}
            />
            <Text style={styles.characterCount}>{inputText.length}/500 characters</Text>
          </View>

          {/* Suggestions */}
          <View style={styles.suggestionsContainer}>
            <Text style={styles.suggestionsTitle}>Suggestions</Text>
            {celebrity.suggestedPrompts && celebrity.suggestedPrompts.length > 0 ? (
              celebrity.suggestedPrompts.map((suggestion, index) => (
                <TouchableOpacity
                  key={index}
                  style={styles.suggestionItem}
                  onPress={() => handleSuggestionPress(suggestion)}
                >
                  <Text style={styles.suggestionText}>{suggestion}</Text>
                </TouchableOpacity>
              ))
            ) : (
              <Text style={styles.noSuggestionsText}>No suggestions available</Text>
            )}
          </View>

          {/* Space for button */}
          <View style={styles.buttonSpacer} />
        </ScrollView>
      </TouchableWithoutFeedback>

      {/* Preview Button */}
      <View style={styles.buttonContainer}>
        <TouchableOpacity style={styles.previewButton} onPress={handlePreview} activeOpacity={0.8}>
          <Text style={styles.previewButtonText}>Preview</Text>
        </TouchableOpacity>
      </View>
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: pxToVw(20),
    paddingVertical: pxToVh(14),
    zIndex: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowRadius: 10,
    shadowOpacity: 0.1,
    borderBottomWidth: 0.3,
    borderBottomColor: 'rgba(203, 213, 225, 0.6)',
  },
  backButton: {
    width: pxToVw(44),
    height: pxToVw(44),
    borderRadius: pxToVw(22),
    backgroundColor: COLORS.gradientLight1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  headerTitleContainer: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  headerTitle: {
    fontSize: pxToVh(18),
    fontWeight: '700',
    color: COLORS.text,
    letterSpacing: -0.5,
  },
  placeholder: {
    width: pxToVw(44),
  },
  profileCardContainer: {
    paddingHorizontal: pxToVw(20),
    paddingVertical: pxToVh(12),
  },
  profileCard: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: COLORS.card,
    padding: pxToVw(16),
    borderRadius: pxToVw(16),
    shadowColor: COLORS.shadow,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.1,
    shadowRadius: 10,
    elevation: 2,
  },
  profileImage: {
    width: pxToVw(46),
    height: pxToVw(46),
    borderRadius: pxToVw(23),
    marginRight: pxToVw(12),
  },
  profileInfo: {
    flex: 1,
  },
  profileName: {
    fontSize: pxToVh(16),
    fontWeight: '600',
    color: COLORS.text,
  },
  profileDescription: {
    fontSize: pxToVh(13),
    color: COLORS.textLight,
    marginTop: pxToVh(2),
  },
  changeButton: {
    paddingHorizontal: pxToVw(12),
    paddingVertical: pxToVh(6),
  },
  changeButtonText: {
    fontSize: pxToVh(14),
    fontWeight: '500',
    color: COLORS.primary,
  },
  questionContainer: {
    paddingHorizontal: pxToVw(20),
    marginTop: pxToVh(8),
    marginBottom: pxToVh(12),
  },
  questionText: {
    fontSize: pxToVh(16),
    fontWeight: '500',
    color: COLORS.text,
  },
  inputContainer: {
    marginHorizontal: pxToVw(20),
    borderWidth: 1,
    borderColor: COLORS.primary,
    borderRadius: pxToVw(12),
    padding: pxToVw(16),
    minHeight: pxToVh(150),
  },
  textInput: {
    fontSize: pxToVh(16),
    color: COLORS.text,
    padding: 0,
    minHeight: pxToVh(100),
    textAlignVertical: 'top',
  },
  characterCount: {
    fontSize: pxToVh(12),
    color: COLORS.textMuted,
    alignSelf: 'flex-end',
    marginTop: pxToVh(8),
  },
  suggestionsContainer: {
    marginTop: pxToVh(20),
    marginHorizontal: pxToVw(20),
    padding: pxToVw(16),
    backgroundColor: COLORS.card,
    borderRadius: pxToVw(12),
    borderWidth: 1,
    borderColor: COLORS.borderLight,
  },
  suggestionsTitle: {
    fontSize: pxToVh(16),
    fontWeight: '600',
    color: COLORS.text,
    marginBottom: pxToVh(12),
  },
  suggestionItem: {
    paddingVertical: pxToVh(10),
    borderBottomWidth: 1,
    borderBottomColor: COLORS.borderLight,
  },
  suggestionText: {
    fontSize: pxToVh(14),
    color: COLORS.primary,
  },
  buttonContainer: {
    position: 'absolute',
    bottom: pxToVh(20),
    left: pxToVw(20),
    right: pxToVw(20),
    paddingBottom: pxToVh(20),
  },
  previewButton: {
    backgroundColor: COLORS.primary,
    borderRadius: pxToVw(10),
    paddingVertical: pxToVh(14),
    alignItems: 'center',
    justifyContent: 'center',
  },
  previewButtonText: {
    color: 'white',
    fontSize: pxToVh(16),
    fontWeight: '600',
  },
  scrollContent: {
    paddingBottom: pxToVh(20),
  },
  buttonSpacer: {
    height: pxToVh(80),
  },
  noSuggestionsText: {
    fontSize: pxToVh(14),
    color: COLORS.textMuted,
    textAlign: 'center',
    marginTop: pxToVh(10),
  },
});

export default EnterText;
